package com.wlyuan.open.scanner.application.handler.incr;

import com.wlyuan.open.dto.OpenContractSyncDTO;
import com.wlyuan.open.scanner.assembler.ScannerContractAssembler;
import com.wlyuan.open.scanner.constant.ScannerCodeEnum;
import com.wlyuan.open.scanner.repository.ContractRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Optional;

/**
 * @author lijing
 * @description 合同 增量 listener
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ContractIncrHandler extends BaseIncrHandler<OpenContractSyncDTO> {
    private final ContractRepository contractRepository;

    @Override
    public OpenContractSyncDTO process(Long contractId) {
        logger.info("合同增量同步：{}", contractId);
        return Optional.ofNullable(contractId).map(id -> {
            var contract = contractRepository.getById(id);
            return ScannerContractAssembler.assemble(contract);
        }).orElse(null);
    }

    @Override
    public void incrByTenantId(Long tenantId) {
        contractRepository.getByTenantId(tenantId);
    }

    @Override
    public void incrByTime(Long tenantId, String startTime, String endTime) {
        var list = tenantId == null ? contractRepository.getByTime(startTime, endTime) : contractRepository.getByTenantIdTime(tenantId, startTime, endTime);
        if (CollectionUtils.isEmpty(list)) {
            logger.info("根据时间{},{}数据为0", startTime, endTime);
            return;
        }
        logger.info("根据时间{},{}数据为：{}", startTime, endTime, list.size());
        list.parallelStream().forEach(id -> increment(id));
        logger.info("同步完成");
    }

    @Override
    public String getSyncType() {
        return ScannerCodeEnum.CONTRACT.getVal();
    }
}
